package com.example.service.impl;

import com.example.entity.Menu;
import com.example.mapper.MenuMapper;
import com.example.pageutils.MyPageHelper;
import com.example.pageutils.PageRequest;
import com.example.pageutils.PageResult;
import com.example.result.CommonResult;
import com.example.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    /**新增
     * @param menu
     * @return
     */
    @Override
    public Integer addpMenuTree(Menu menu) {
        int i = menuMapper.add(menu);
        return i;
    }

    /**全查
     * @param
     * @param menuName
     * @return
     */
    @Override
    public CommonResult getMenu(String menuName) {
        return CommonResult.ok(MyPageHelper.getPageResult(menuMapper.getMenu(menuName)));
    }


    /*树查询*/
    @Override
    public List<Menu> getMenuTree() {
        List<Menu> list=menuMapper.select();
        ArrayList<Menu> arrayList = new ArrayList<>();
        for (Menu menu : list) {
            if(menu.getParentid() ==0 ){
                arrayList.add(getChild(menu,list));
            }
        }
        System.out.println(arrayList);
        return arrayList;
    }

    /**修改
     * @param menu
     * @return
     */
    @Override
    public Integer updateMenu(Menu menu) {
        int i = menuMapper.update(menu);
        return i;
    }

    /**删除
     * @param id
     * @return
     */
    @Override
    public Integer deleMenu(Integer id) {
        Menu menu = new Menu();
        menu.setDelFlag(1);
        int i = menuMapper.delete(id);
        return i;
    }


    private Menu getChild(Menu menu, List<Menu> list) {
        ArrayList<Menu> list1 = new ArrayList<>();
        for (Menu menu1 : list) {
            if(menu.getId().equals(menu1.getParentid())){
                list1.add(getChild(menu1,list));
            }
        }
        menu.setChilds(list1);
        return menu;
    }


}
